<template>
  <div>
 <!-- 搜索区域卡片 -->
  <el-card class="box-card">
    <!-- 搜索表单 -->
    <el-form :inline="true" ref="searchForm" :model="searchForm" class="demo-form-inline">
  <el-form-item label="用户名" prop="username">
    <el-input size="small" clearable v-model="searchForm.username" placeholder="用户名" style="width: 130px;"></el-input>
  </el-form-item>
  <el-form-item label="手机号" prop="phone">
    <el-input size="small" clearable v-model="searchForm.phone" placeholder="手机号" style="width: 140px;"></el-input>
  </el-form-item>
  <el-form-item label="性别" prop="gender">
    <el-select size="small" v-model="searchForm.gender" placeholder="性别" style="width: 80px;">
      <el-option label="-" value=""></el-option>
      <el-option label="男" value="0"></el-option>
      <el-option label="女" value="1"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="创建时间" prop="createTime">
    <el-date-picker
      clearable
     style="width: 220px;"
      size="small"
      v-model="searchForm.createTime"
      type="daterange"
      align="right"
      unlink-panels
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      :picker-options="pickerOptions">
    </el-date-picker>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" size="small" @click="onSearch">查询</el-button>
    <el-button type="primary" size="small" @click="onReset('searchForm')">重置</el-button>
  </el-form-item>
</el-form>
  </el-card>
  <!-- 数据展示表格 -->
  <el-card class="table-card">
     <!-- 批量删除按钮 -->
    <el-button type="danger" size="small" @click="batchDelete" class="batch-delete-btn"><i class="el-icon-delete"></i>批量删除</el-button>
    <!-- 添加按钮 -->
    <el-button type="success" size="small" @click="openDialog" class="btn-add" ><i class="el-icon-plus"></i>添加用户</el-button>
  <el-table
      :data="userList"
      style="width: 100%"
       @selection-change="handleSelectionChange">
      <el-table-column
      type="selection"
      width="55">
    </el-table-column>
      <el-table-column
        prop="id"
        label="编号"
        width="60">
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        width="100">
      </el-table-column>
      <el-table-column
        prop="gender"
        label="性别"
        width="80"
        :formatter="formatSex">
      </el-table-column>
      <el-table-column
        prop="nickname"
        label="昵称"
        width="110">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="手机号">
      </el-table-column>
       <el-table-column
        prop="status"
        label="帐号状态">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 1" class="status-active">启用</span>
          <span v-else-if="scope.row.status === 0" class="status-disabled">禁用</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间">
      </el-table-column>
      <el-table-column
      fixed="right"
      label="操作"
      width="200">
      <template slot-scope="scope" >
        <el-button @click="handleEdit(scope.$index, scope.row)" size="mini" class="btn-edit" type="primary">编辑</el-button>
         <!-- 帐号状态切换按钮 -->
        <el-button @click="handleStatusChange(scope.$index, scope.row)" size="mini" class="btn-status" type="info">
          {{ scope.row.status === 1 ? '禁用' : '启用' }}
        </el-button>
        <el-button @click="deleteUser(scope.$index,scope.row)" size="mini" class="btn-delete" type="danger">删除</el-button>
      </template>
    </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="pagination.pageSizes"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      background
      v-loading="isLoading">
    </el-pagination>
</el-card>

<!-- 添加/修改用户对话框 -->
  <el-dialog :title="dialogTitle" :visible.sync="userDialogVisible" width="500px">
    <el-form ref="userForm" :model="userForm" class="demo-form-inline" label-width="80px">
  <el-form-item label="用户名" prop="username">
    <el-input size="small" clearable v-model="userForm.username" placeholder="用户名" style="width: 350px;"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input size="small" clearable v-model="userForm.password" placeholder="密码" style="width: 350px;"></el-input>
  </el-form-item>
  <el-form-item label="昵称" prop="nickname">
    <el-input size="small" clearable v-model="userForm.nickname" placeholder="昵称" style="width: 350px;"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input size="small" clearable v-model="userForm.email" placeholder="邮箱" style="width: 350px;"></el-input>
  </el-form-item>
  <el-form-item label="手机号" prop="phone">
    <el-input size="small" clearable v-model="userForm.phone" placeholder="手机号" style="width: 350px;"></el-input>
  </el-form-item>
  <el-form-item label="性别" prop="gender">
    <el-select size="small" v-model="userForm.gender" placeholder="性别" style="width: 350px;">
      <el-option label="-" value=""></el-option>
      <el-option label="男" value="0"></el-option>
      <el-option label="女" value="1"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" size="small" @click="handleAdd">确定</el-button>
    <el-button type="primary" size="small" @click="resetUserDialog('userForm')">取消</el-button>
  </el-form-item>
</el-form>
  </el-dialog>
  
  

</div>
</template>

<script>
import {getUserList, deleteUser, updateUserStatus, batchDeleteUsers, addUser} from '@/api/user';

export default {
  name: 'AllUsers',
  data() {
    return {
      // 所有用户列表
      userList: [],
      // 搜索条件
      searchForm: {
        username: '',
        phone: '',
        gender: null,
        createTime: [],
        beginTime: '',
        endTime: ''
      },
      // 新增/修改用户表单数据
      userForm: {
        id: '',
        username: '',
        password: '',
        nickname: '',
        email: '',
        phone: '',
        gender: null,
        createTime: ''
      },
      // 分页参数 - 独立管理
      pagination: {
        page: 1,       // 当前页码
        pageSize: 3,      // 每页显示条数（默认修改为5）
        total: 0,         // 总记录数
        pageSizes: [3, 5, 7, 10, 15] // 可选择的每页条数
      },
      // 加载状态
      isLoading: false,
      // 选中的用户ID列表
      selectedIds: [],
      // 日期选择器的快捷选项
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      // 对话框标题
      dialogTitle: '添加用户',
      // 对话框的可见状态
      userDialogVisible: false,

    };
  },
  methods: {
    // 格式化性别显示
    formatSex(row, column) {
      return row.gender === 0 ? '男' : row.gender === 1 ? '女' : '';
    },

    // 处理编辑按钮点击
    handleEdit(index, row) {
      
    },

    // 打开对话框
    openDialog() {
      this.dialogTitle = '添加用户';
      this.userDialogVisible = true;
    },
    //执行添加用户操作
    handleAdd() {
      addUser(this.userForm).then(res => {
        if(res.data && res.data.code !== 1) {
          this.$message.error('用户添加失败: ' + (res.data?.msg || '服务器错误'));
        } else {
          this.pagination.page = 1;
          this.$message({ type: 'success', message: '用户添加成功' });
          // 清空表单数据
          this.resetUserDialog('userForm');
          this.fetchAllUsers();
        }

        //关闭对话框
        this.userDialogVisible = false;
      })
    },

    // 处理查询按钮点击
    onSearch() {
      this.searchForm.beginTime = this.searchForm.createTime[0]
      this.searchForm.endTime = this.searchForm.createTime[1]
      this.fetchAllUsers();

    },

    //处理复选框选中事件
    handleSelectionChange(selection) {
      // 从选中的行数据中提取ID并赋值给selectedIds数组
      this.selectedIds = selection.map(row => row.id);
      },
      
    // 批量删除完成实现
    batchDelete() {
      // 检查是否有选中的用户
      if (this.selectedIds.length === 0) {
        this.$message.warning('请先选择要删除的用户');
        return;
      }
      
      this.$confirm(`确定要删除选中的 ${this.selectedIds.length} 个用户吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.isLoading = true;
        // 使用批量删除接口，直接传递id列表
        batchDeleteUsers(this.selectedIds).then(res => {
          this.isLoading = false;
          if (res.data && res.data.code === 1) {
            this.$message({ type: 'success', message: `成功删除 ${this.selectedIds.length} 个用户!` });
            // 清空选中状态
            this.selectedIds = [];
            this.fetchAllUsers(); // 重新加载用户列表
          } else {
            this.$message.error('批量删除失败: ' + (res.data?.msg || '服务器错误'));
          }
        }).catch(err => {
          this.isLoading = false;
          this.$message.error('批量删除失败: ' + (err.data?.msg || '网络错误'));
        });
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消批量删除' });
      });
    },

    //处理搜索框重置按钮
    onReset(formName) {
      this.$refs[formName].resetFields();
      // 重置分页参数
      this.pagination.page = 1;
      this.fetchAllUsers();
    },
    //处理对话框取消按钮点击事件
    resetUserDialog(formName) {
      this.userDialogVisible = false;
      this.$refs[formName].resetFields();
    },
    // 获取所有用户
    fetchAllUsers() {
      this.isLoading = true;
      getUserList({
        page: this.pagination.page,
        pageSize: this.pagination.pageSize,
        username: this.searchForm.username,
        phone: this.searchForm.phone,
        gender: this.searchForm.gender,
        beginTime: this.searchForm.beginTime,
        endTime: this.searchForm.endTime
      }).then(res => {
        this.isLoading = false;
        // 更健壮的响应数据处理
        if (res && res.data && res.data.code === 1 && res.data.data && res.data.data.records) {
          this.userList = res.data.data.records;
          this.pagination.total = res.data.data.total;
        } else {
          this.userList = [];
          this.pagination.total = 0;
          this.$message.error('获取用户列表失败: 数据格式异常');
        }
      }).catch(err => {
        this.isLoading = false;
        console.log('获取用户列表错误:', err);
        this.$message.error('获取用户列表失败: ' + (err.data?.msg || '网络错误'));
      })
    },
    
    // 切换用户状态（启用/禁用）
    handleStatusChange(index, row) {
      // 计算新状态（0变为1，1变为0）
      const newStatus = row.status === 1 ? 0 : 1;
      this.isLoading = true;
      updateUserStatus(row.id, newStatus).then(res => {
        this.isLoading = false;
        if (res.data.code === 1) {
          this.$message({ type: 'success', message: `用户已${newStatus === 1 ? '启用' : '禁用'}` });
          this.fetchAllUsers(); // 重新加载用户列表
        } else {
          this.$message.error('状态更新失败: ' + (res.data?.msg || '未知错误'));
        }
      }).catch(err => {
        this.isLoading = false;
        this.$message.error('状态更新失败: ' + (err.data?.msg || '网络错误'));
      })
    },

    // 删除用户
    deleteUser(id) {
      this.$confirm('确定要删除这个用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isLoading = true;
        deleteUser(id).then(res => {
          this.isLoading = false;
          if (res.data.code === 1) {
            this.$message({ type: 'success', message: '删除成功!' });
            this.fetchAllUsers(); // 重新加载用户列表
          } else {
            this.$message.error('删除失败: ' + (res.data?.msg || '未知错误'));
          }
        }).catch(err => {
          this.isLoading = false;
          this.$message.error('删除失败: ' + (err.data?.msg || '网络错误'));
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' });
      });
    },

    // 页面大小改变事件
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      // 重置到第一页，避免在数据量不足时出现空白页
      //this.pagination.pageNum = 1;
      this.fetchAllUsers();
    },
    
    // 当前页改变事件
    handleCurrentChange(val) {
      this.pagination.page = val;
      this.fetchAllUsers();
    },

  },
  created() {
    this.fetchAllUsers();
  }
};
</script>

<style scoped>
.box-card {
  width: 100%;
  height: 70px;
  text-align: left;
  margin-bottom: 20px;
}

.btn-edit, .btn-delete, .btn-status {
  width: 50px;
}

/* 批量删除按钮样式 */
.batch-delete-btn {
  margin-bottom: 10px;
  float: left;
  margin-right: 5px; /* 添加一点右边距，让两个按钮不会完全重叠 */
}

/* 添加用户按钮样式 */
.btn-add {
  margin-bottom: 10px;
  float: left;
}
.status-active {
  color: #67c23a;
}

.status-disabled {
  color: #f56c6c;
}
</style>